// app/signin/page.tsx - 登录页面

"use client";

import { useState, useEffect, Suspense } from 'react'
import { Button, Input, message, Tabs, Modal } from 'antd'
import { UserOutlined, WechatOutlined } from '@ant-design/icons'
import { useRouter, useSearchParams } from 'next/navigation'
import { authService } from '@/lib/services/auth'
import { AuthProvider, useAuth } from '@/app/context/auth-context'
import PhoneInput from '@/app/components/auth/phone-input'
import VerificationCodeInput from '@/app/components/auth/verification-code-input'
import PasswordInput from '@/app/components/auth/password-input'
import LoginForm from "@/app/components/auth/login-form"

function SignInContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const { 
    loginType,
    setLoginType,
    username,
    setUsername,
    usernameError,
    phone,
    verificationCode,
    password,
    validatePhone,
    validateUsername,
    validatePassword,
    validateVerificationCode
  } = useAuth()

  // 提交登录
  const handleSubmit = async () => {
    try {
      if (loginType === 'phone') {
        // 手机号登录验证
        const isPhoneValid = validatePhone(phone)
        const isVerificationCodeValid = validateVerificationCode(verificationCode)
        if (!isPhoneValid || !isVerificationCodeValid) return

        setLoading(true)
        console.log('=== 开始手机号登录 ===');
        const response = await authService.login({
          username_or_phone: phone,
          verification_code: verificationCode
        })
        
        console.log('登录响应:', response);
        
        if (response.code === 200 && response.data) {
          const loginData = response.data;
          if (loginData.access_token && loginData.refresh_token) {
            message.success('登录成功')
            console.log('准备跳转到 /explore/apps');
            router.push('/explore/apps')
          } else {
            console.error('登录失败：未获取到认证令牌');
            message.error(loginData.message || '登录失败：未获取到认证令牌')
          }
        } else {
          console.error('登录失败：', response.message);
          message.error(response.message || '登录失败，请重试')
        }
      } else if (loginType === 'password') {
        // 账号密码登录验证
        const isUsernameValid = validateUsername(username)
        const isPasswordValid = validatePassword(password)
        if (!isUsernameValid || !isPasswordValid) return

        setLoading(true)
        console.log('=== 开始账号密码登录 ===');
        const response = await authService.login({
          username_or_phone: username,
          password
        })
        
        console.log('登录响应:', response);
        console.log('登录响应数据:', response.code, response.data, response.message);
        if (response.code === 200 && response.data) {
          const loginData = response.data;
          if (loginData.access_token && loginData.refresh_token) {
            message.success('登录成功')
            console.log('准备跳转到 /explore/apps');
            router.push('/explore/apps')
          } else {
            console.error('登录失败：未获取到认证令牌');
            message.error(loginData.message || '登录失败：未获取到认证令牌')
          }
        } else {
          console.error('登录失败：', response.message);
          message.error(response.message || '登录失败，请重试')
        }
      }
    } catch (error) {
      console.error('登录过程发生错误:', error);
      message.error('登录失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 手机号登录表单
  const PhoneLoginContent = (
    <form onSubmit={(e) => {
      e.preventDefault();
      handleSubmit();
    }} className="space-y-6">
      <PhoneInput />
      <VerificationCodeInput />
      <Button
        type="primary"
        size="large"
        block
        loading={loading}
        htmlType="submit"
      >
        登录
      </Button>
    </form>
  )

  // 账号密码登录表单
  const PasswordLoginContent = (
    <form onSubmit={(e) => {
      e.preventDefault();
      handleSubmit();
    }} className="space-y-6">
      <div className="mb-4">
        <Input
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          status={usernameError ? 'error' : ''}
          prefix={<UserOutlined />}
          placeholder="请输入用户名"
          size="large"
        />
        {usernameError && (
          <div className="mt-1 text-red-500 text-sm">{usernameError}</div>
        )}
      </div>

      <PasswordInput />

      <Button
        type="primary"
        size="large"
        block
        loading={loading}
        htmlType="submit"
      >
        登录
      </Button>
    </form>
  )

  // 微信登录占位
  const WechatLoginContent = (
    <div className="py-8 text-center">
      <WechatOutlined className="text-6xl text-green-500 mb-4" />
      <div className="text-gray-500">微信登录功能开发中...</div>
    </div>
  )

  const items = [
    {
      key: 'phone',
      label: '手机号登录',
      children: PhoneLoginContent
    },
    {
      key: 'password',
      label: '账号密码登录',
      children: PasswordLoginContent
    },
    {
      key: 'wechat',
      label: '微信登录',
      children: WechatLoginContent
    }
  ]

  return (
    <>
      <div className="min-h-[280px]">
        <Tabs
          activeKey={loginType}
          items={items}
          onChange={(key) => setLoginType(key as 'phone' | 'password' | 'wechat')}
          centered
        />
      </div>
      
      <div className="flex justify-between text-gray-500 mt-4">
        <Button type="link" onClick={() => router.push('/signup')}>
          注册账号
        </Button>
        <Button type="link" onClick={() => {
          setLoginType('phone');
          setModalVisible(true);
        }}>
          忘记密码？
        </Button>
      </div>

      <Modal
        title="提示"
        open={modalVisible}
        onOk={() => setModalVisible(false)}
        onCancel={() => setModalVisible(false)}
        cancelButtonProps={{ style: { display: 'none' } }}
        centered
        width={400}
      >
        <p>忘记账号密码请用手机号进行登录</p>
      </Modal>
    </>
  )
}

export default function SignInPage() {
  return (
    <AuthProvider>
      <Suspense fallback={
        <div className="min-h-screen flex items-center justify-center bg-gray-50">
          <div className="text-center">
            <div className="text-gray-500">加载中...</div>
          </div>
        </div>
      }>
        <SignInContent />
      </Suspense>
    </AuthProvider>
  )
}
